package com.atguigu.tingshu.search.consumer;


import com.atguigu.tingshu.search.service.ItemService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/***
 * 专辑订单支付后的后续处理
 */
@Component
@Log4j2
public class OrderAfterPaidSearchConsumer {

    @Autowired
    private ItemService itemService;

    /**
     * 增加专辑的热度值
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(queues = "order_after_paid_search_queue")
    public void orderAfterPaidSearchMessageConsumerListener(Message message, Channel channel){
        // 从message中获取orderNo
        String orderNo = new String(message.getBody());
        // 获取messageProperties
        MessageProperties messageProperties = message.getMessageProperties();
        // 获取消息编号
        long deliveryTag = messageProperties.getDeliveryTag();
        try{
            // 增加热度值
            itemService.updateHotScore(orderNo);
            // 确认消息
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            // 判断是否是重试的消息
            if (messageProperties.isRedelivered()){
                // 是重试的,将错误信息记录到日志后拒绝消息
                log.error("增加热度值失败，失败原因：" +
                        e.getMessage() + "。订单: " + orderNo );
                // 拒绝消息
                channel.basicReject(deliveryTag,false);
            }else {
                // 不是重试消息，放回队列再消费一次
                channel.basicReject(deliveryTag,true);
            }
        }
    }
}
